<template>
	<div class="zh-question">
		
		<!--  -->
		<div class="pointMark_video">
			
			<video-player  class="video-player vjs-custom-skin"
				ref="videoPlayer"
				:playsinline="true"
				:options="playerOptions"
				@play="onPlayerPlay($event)"
				@pause="onPlayerPause($event)"
				>
			</video-player>
		
		</div>
		<div class="publishFrom">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="测试名称" prop="test_name">
					<el-input v-model.trim="ruleForm.test_name" maxlength="20" placeholder="最多可以输入20个字"></el-input>
				</el-form-item>
				<div class="publishFrom_if clear">
					<el-form-item label="打点时间" prop="test_time" class="publishFrom_if_l fl">
						<span>
							<el-time-picker
							   v-model="ruleForm.test_time"
							   value-format="HH:mm:ss"
							   :arrow-control="true"
							   :picker-options="{
							   	 format: 'HH:mm:ss',
							     selectableRange: timeMax
							   }"
							   placeholder="任意时间点">
							 </el-time-picker>
						</span>
						<i class="el-icon-location" @click="getVideoPlayTime()"></i>
					</el-form-item>
					<!--  -->
					<div class="publishFrom_if_r fr">
							
						<el-form-item class="buttonCSS" label-width="0" >
							<!-- <el-button @click="resetForm('ruleForm')" type="primary" plain>取消</el-button> -->
							<el-button type="primary" @click="submitForm('ruleForm')">添加测试</el-button>
						</el-form-item>
					</div>
				</div>
				
			</el-form>
		</div>
		<div class="publishFrom_table">
			<template>
				<el-table
				border
				:data="pointData"
				style="width: 100%">
					<el-table-column
						prop="test_name"
						label="测试名称"
						width="300">
					</el-table-column>
					<el-table-column
						 align="center"
						prop="question_count"
						label="试题数量"
						width="80">
					</el-table-column>
					<el-table-column
					 	align="center"
						prop="test_time"
						label="测试时间"
						width="120">
					</el-table-column>
					<el-table-column
					 	align="center"
						prop="test_record_user_count"
						label="测试人次"
						width="80">
					</el-table-column>
					<el-table-column
					    label="操作"
					    align="center"
					    width="118">
					    <template slot-scope="scope">
					    	 <el-button @click="editteTest(scope.row)" type="text" size="small">编辑</el-button>
					      <el-button @click="deleteTest(scope.row)" type="text" size="small">删除</el-button>
					    </template>
					  </el-table-column>
				</el-table>
			</template>
			
		</div>
		<!--  -->
		<el-dialog
			title="编辑题干"
			:visible.sync="questionVisible"
			width="800px"
			:close-on-click-modal="false"
			@close="closeQuestion">
			<div class="questionView">
			
				<el-tabs v-model="tabTempIndex" type="card" 
				editable @edit="handleTabsEdit"  class="addAlbum_msg">
				  <el-tab-pane
				    v-for="(item, index) in ruleForm.test_data"
				    :label="item.title"
				    :name="item.name"
				    :key="index" >
					   	<div class="questionView_c">
					   		<el-form  label-width="85px" :model="item" :ref="'questionForm' + index" :rules="question">
					   			<el-form-item label="题干" prop="problem">
					   			   <el-input v-model.trim="item.problem" 
					   			   type="textarea"
					   			   resize="none"  :rows="4"
					   			   placeholder="点击编辑单选题干，并选择正确答案"></el-input>
					   			</el-form-item>
					   			<el-form-item label="A" prop="A">
					   			   <el-input v-model.trim="item.A"  
					   			   placeholder="点击编辑选项"></el-input>
					   			</el-form-item>
					   			<el-form-item label="B" prop="B">
					   			   <el-input v-model.trim="item.B"  
					   			   placeholder="点击编辑选项"></el-input>
					   			</el-form-item>
					   			<el-form-item label="C" prop="C">
					   			   <el-input v-model.trim="item.C"  
					   			   placeholder="点击编辑选项"></el-input>
					   			</el-form-item>
					   			<el-form-item label="D"  prop="D">
					   			   <el-input v-model.trim="item.D"  
					   			   placeholder="点击编辑选项"></el-input>
					   			</el-form-item>
					   			<el-form-item label="正确答案" prop="answer">
					   				<el-radio-group v-model="item.answer">
					   					<el-radio label="A"></el-radio>
					   					<el-radio label="B"></el-radio>
					   					<el-radio label="C"></el-radio>
					   					<el-radio label="D"></el-radio>
					   				</el-radio-group>
					   			</el-form-item>
					   			<el-form-item label="解析" prop="resolve">
					   			   <el-input v-model.trim="item.resolve" 
					   			   type="textarea"
					   			   resize="none"  :rows="4"
					   			   placeholder="点击编辑解析"></el-input>
					   			</el-form-item>
					   		</el-form>
					   	</div>
				  </el-tab-pane>
				</el-tabs>
				<div class="btnCss">
					<el-button type="primary" @click="saveTest" v-if="ruleForm.test_data.length !== 0">生成测试点</el-button>
				</div>
			</div>
			<span slot="footer" class="">
				
			</span>
		</el-dialog>
		<!--  -->
		<el-dialog
			title="边看边测"
			:visible.sync="sideLookVisible"
			width="800px"
			:close-on-click-modal="false">
			<div class="sideLook">
				<el-tabs v-model="tabTempIndex" type="card" 
				 class="addAlbum_msg">
				  <el-tab-pane
				    v-for="(item, index) in testQuestionData"
				    :label="item.title"
				    :name="item.name"
				    :key="index" >
				    	<el-form  label-width="60px">
							<el-form-item label="题干">
								<div class="sideLook-txt">
									{{item.problem}}
							</div>
							</el-form-item>
							<el-form-item label="A">
								<div class="sideLook-txt">{{item.A}}</div>
							</el-form-item>
							<el-form-item label="B">
								<div class="sideLook-txt">{{item.B}}</div>
							</el-form-item>
							<el-form-item label="C">
								<div class="sideLook-txt">{{item.C}}</div>
							</el-form-item>
							<el-form-item label="D">
								<div class="sideLook-txt">{{item.D}}</div>
							</el-form-item>
							<el-form-item label="正确答案" label-width="80px">
								<!-- <el-radio-group v-model="item.answer"> -->
								<el-radio-group v-model="answerQuestionData[index].answer">
									<el-radio label="A"></el-radio>
									<el-radio label="B"></el-radio>
									<el-radio label="C"></el-radio>
									<el-radio label="D"></el-radio>
								</el-radio-group>
							</el-form-item>
							
							<el-form-item label="解析" prop="resolve">
								<div class="sideLook-txt" v-html="item.resolve"></div>
							</el-form-item>
							<el-form-item  label-width="0" class="buttonCSS">
								<el-button type="primary" @click="answerTestQuestion()">确定</el-button>
							</el-form-item>
						</el-form>

				    </el-tab-pane>
				</el-tabs>
				
			</div>
			<div slot="footer" class="dialog-footer"></div>
		</el-dialog>
		<!--  -->
		<el-dialog
			title="测试"
			:visible.sync="testVisible"
			width="640px"
			custom-class="checkoutVisible"
			:close-on-click-modal="false">
			<div class="testVisible">
				<h3>还有<i>1</i>题未通过，继续努力</h3>
				<h3>恭喜你，通过测试</h3>
				<template>
					<el-table
					border
					:data="tableData2"
					style="width: 100%">
						<el-table-column
						prop="name"
						label="题号"
						width="50">
						</el-table-column>
						<el-table-column
						prop="name2"
						label="题目标题"
						width="180"
						show-overflow-tooltip>
						</el-table-column>
						<el-table-column
						prop="name3"
						label="测验时间"
						width="120"
						show-overflow-tooltip>
						</el-table-column>
						<el-table-column
						prop="name4"
						label="测验名称"
						width="168"
						show-overflow-tooltip>
						</el-table-column>
						<el-table-column
						prop="测验时间"
						width="60"
						label="结果">
							<template slot-scope="scope">
								<i class="el-icon-close"></i>
								<i class="el-icon-check"></i>
							</template>
						</el-table-column>
					</el-table>
				</template>
			</div>
			<div slot="footer" class="dialog-footer buttonCSS">
				<el-button type="primary">重新测试</el-button>
			</div>
		</el-dialog>

	</div>
</template>
<script>
	
	// import menuLink from './men uLink.vue'
	// import SWF_URL from 'videojs-swf/dist/video-js.swf';
	export default {
		props : ['compParam','activeIndex'],
		name: '',
		data() {
			return {
				editBol: false,
				editObj: null,
				sideLookVisible: false,
				sideLook: '',
				testVisible: false,

				questionVisible: false,
				editableTabsValue: 0,
				watchPlayTimeOut:null,
				watchPlayTimeArr:[],
				answerTimeArr:[],
				testQuestionData:[],
				answerQuestionData:[],
				opTestID:0,
				editableTabsEle:{
					title:  '第1题',
					name: '1',
					problem:'',
					A:'',
					B:'',
					C:'',
					D:'',
					answer:''
				},
				tabIndex: 1,
				tabTempIndex: '0',
				pointData:[],
				thisIndex:'3',
				timeMax: '00:00:00 - 00:00:00',
				ruleForm: {
					id:0,
					test_name: '', //视频名称
					test_time: '',
					test_data:[],
				},
				rules: {
					test_name: [
						{ required: true, message: '请输入测试名称', trigger: 'blur' },
						// { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					test_time: [
						{ required: true, message: '请输入打点时间', trigger: 'blur' },
					]
				},
				playerOptions : {
				    loop: false,
				    height: '360',
			        sources: [{
			           type: "application/x-mpegURL", // application/x-mpegURL rtmp/mp4类型
			            src: "blabla"
			        }],
			        // techOrder: ['flash'],
			        autoplay: false,
			        controls: true,
			        poster: "",
					controlBar: {
			          	timeDivider: true,
			         	durationDisplay: true,
			         	remainingTimeDisplay: false,
			          	fullscreenToggle: true  //全屏按钮
				    },
				    // flash: {swf: SWF_URL },
				},
				  tableData2: [
					{
						name: 1,
						name2: '标题标题',
						name3: '00:20:20',
						name4: '标题标题',
					}
				],
				question: {
					problem: [
						{required: true, message: '内容不能为空', trigger: 'blur'}
					],
					A: [
						{required: true, message: '内容不能为空', trigger: 'blur'}
					],
					B: [
						{required: true, message: '内容不能为空', trigger: 'blur'}
					],
					C: [
						{required: true, message: '内容不能为空', trigger: 'blur'}
					],
					D: [
						{required: true, message: '内容不能为空', trigger: 'blur'}
					],
					answer: [
						{required: true, message: '请选择正确答案', trigger: 'change'}
					]
				}
			
			}
		},

		
	    mounted(){
	    	this.initFunc();
	    },
	    beforeDestroy(){
	    	this.$refs.videoPlayer && this.$refs.videoPlayer.player.reset()
	    },
		methods: {
			initFunc(){
				this.$refs.videoPlayer.player.src({ type : "application/x-mpegURL", src : this.compParam.play_url }) ;
				// this.$refs.videoPlayer.options.sources[0].src =  this.compParam.play_url;
				this.resetForm('ruleForm');
				this.getTestList();
				this.ruleForm.test_data = [];
            	this.questionVisible = false;
            	this.timeMax = '00:00:00 - '+ this.compParam.length;
			},
		
			watchPlayProgress(){
				if( this.pointData.length > 0 ){
					this.watchPlayTimeArr = getOneColumn( this.pointData , 'test_time' );
			        this.watchPlayTimeOut = setInterval(() => {
			        	parseInt(this.activeIndex) !== 3 && clearInterval( this.watchPlayTimeOut);

			    		var nowTime = formatSeconds( this.$refs.videoPlayer.player.currentTime() );
						var playerTime  = nowTime.hour+':'+nowTime.minute+':'+nowTime.second;
						var position = this.watchPlayTimeArr.indexOf( playerTime );
						if( position > -1  && this.answerTimeArr.indexOf( playerTime ) === -1 ){
							//答题弹框
							this.$refs.videoPlayer.player.pause();
							this.sideLookVisible = true;
							this.opTestID =  this.pointData[position].id ;
							this.getTestInfo();
						}
			        }, 1000)
				}
				
			},
			closeQuestion(){
				this.editBol = false
				this.questionVisible = false
				this.ruleForm.test_data = []
			},
			editteTest(obj){
				this.editBol = true
				this.editObj = obj
				this.opTestID = obj.id
				this.questionVisible = true
				this.getTestInfo(this.editBol)
	
			
			},
		
			deleteTest(obj){
				let yes = ( data => {
					let success = ( data => {
						this.$message.success(data.msg)
						this.initFunc();
					})
					this.$ajax.delete('api/video/video_test',{params: {id:obj.id},func:{success:success}})
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.test_name+' 删除吗？'});
			},
			getTestInfo(type){
				let success = (data=>{
            		this.testQuestionData = data.data;
            		this.answerQuestionData = [];
            		this.ruleForm.test_data = []
            		
            			let answerArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
            		for( var i = 0 ; i < this.testQuestionData.length ; i++ ){
            			let item = this.testQuestionData[i]
            			this.testQuestionData[i].title = '第'+(i+1)+'题';
            			this.testQuestionData[i].name = i+'';
            			this.answerQuestionData.push({
            				question_id:this.testQuestionData[i].question_id,
            				answer:''
            			})

            			this.testQuestionData[i].answer = answerArr[+this.testQuestionData[i].answer-1]

            			if (type) {
            				this.tabTempIndex  = '0'
            				this.ruleForm.test_data.push({
            					title:  '第'+(i+1)+'题',
            					name: i+'',
            					problem:'',
            					A:item.A,
            					B: item.B,
            					C:item.C,
            					D: item.D,
            					answer:item.answer,
            					resolve: item.resolve,
            					problem: item.problem
            				})
            			}
  
            		}
            	})
            	let fail = ( data =>{

            	})
				this.$ajax.get('api/video/test_question',{params: {id: this.opTestID},func:{success:success,fail:fail}});
			},
			answerTestQuestion(){
				if( getOneColumn(this.answerQuestionData ,  'answer').indexOf('') > -1 ){
					this.$message.warning('请先回答完题目再提交！');
					return false;
				}
				let success = ( data=>{
					var nowTime = formatSeconds( this.$refs.videoPlayer.player.currentTime() );
					var playerTime  = nowTime.hour+':'+nowTime.minute+':'+nowTime.second;
					this.answerTimeArr.push( playerTime );
					this.sideLookVisible = false;
					this.$refs.videoPlayer.player.play();
					this.$message.success(data.msg)
					//this.initFunc();
            	})
            	this.$ajax.post('api/video/test_question',{ test_id:this.opTestID,answer_data:this.answerQuestionData },{func:{success:success}})
			},
			saveTest() {
			
				let forms = this.$refs;
				let validArr = []
				for(let obj in forms) {
					if(obj.indexOf('questionForm') > -1 ) {
				
						this.$refs[`${obj}`].length > 0 && this.$refs[`${obj}`][0].validate((valid) => {
							validArr.push(valid)
						})
					}
				}
				if(validArr.indexOf(false) < 0) {
					this.ruleForm.id = this.compParam.id;
				 		let success = ( data=>{
				 			this.$message.success(data.msg)
				 			this.questionVisible = false
				 			this.$refs.videoPlayer.player.play();
				 			this.resetForm('ruleForm');
							this.getTestList();
							this.ruleForm.test_data = [];
			            	this.questionVisible = false;
		             	})

		           if (this.editBol) {

			           	var newTime = formatSeconds(this.editObj.test_time);
			           	this.ruleForm.test_id =  this.editObj.id
			           	this.ruleForm.test_name = this.editObj.test_name;
			           	this.ruleForm.test_time = this.editObj.test_time
		           		
		           		this.ruleForm.id  = undefined
		           		
		           	this.$ajax.put('api/video/video_test',this.ruleForm,{func:{success:success}})
		           }else{
		           		this.$ajax.post('api/video/video_test',this.ruleForm,{func:{success:success}})
		           }
		            
				}
			},
			getTestList(){
				let success = (data=>{
            		this.pointData = data.data;
            		for (var i = this.pointData.length - 1; i >= 0; i--) {
						var newTime = formatSeconds(this.pointData[i].test_time);
						this.pointData[i].test_time_num = this.pointData[i].test_time;
						this.pointData[i].test_time = newTime.hour+':'+newTime.minute+':'+newTime.second
					}
					this.resolveMark();
            	})
            	let fail = ( data =>{

            	})
				this.$ajax.get('api/video/video_test',{params: {id: this.compParam.id},func:{success:success,fail:fail}})
			},
			getVideoPlayTime(){
				var nowTime = formatSeconds( this.$refs.videoPlayer.player.currentTime() );
				this.ruleForm.test_time = nowTime.hour+':'+nowTime.minute+':'+nowTime.second
			},
			resolveMark(){
				//先删除所有打点
				var dotting_time_element = this.$refs.videoPlayer.player.controlBar.progressControl.el_.children[0].getElementsByClassName('dotting_time');
				if( dotting_time_element.length > 0 ){
					for (var i = dotting_time_element.length - 1; i >= 0; i--) {
						this.$refs.videoPlayer.player.controlBar.progressControl.el_.children[0].removeChild(dotting_time_element[i]);
					}
					
				}
				if( this.pointData.length > 0 ){
					var newTime = this.compParam.length.split(':');
					var total_time_num = parseInt(newTime[0])*3600+parseInt(newTime[1])*60+parseInt(newTime[2]);
					for(var i = 0 ; i < this.pointData.length ; i ++ ){
						var left =  this.pointData[i].test_time_num/total_time_num * 100;
						var	html  = `<div class="dotting_time"  
										style="background:#54b554;
										left: ${left}%;
										width:5px;height:100%;
										position:absolute;z-Index:55;"
										 current_time="">
										<div class="low_source">
											<p class="low_h">${this.pointData[i].test_name}</p>
											
										</div>
									</div>`
						this.$refs.videoPlayer.player.controlBar.progressControl.el_.children[0].insertAdjacentHTML('beforeend',html)
					}
				}
			},
			/**
			 * 改变进度条
			 */
			onSlicePlay() {
			 /*   this.debounce(() => {
			        var normal_currentTime = this.$refs.videoPlayer.player.currentTime();
			        var unnormal_currentTime = this.$refs.videoPlayer.player.currentTime();
			        if (
			            normal_currentTime.toString() ==
			            unnormal_currentTime.toString()
			        ) {
			            this.$refs.videoPlayer.player.pause();
			            this.$refs.videoPlayer.player.play();
			        }
			    }, 100);*/

			},
			//延迟处理
			debounce(func, wait, immediate) {
			    let timeout, args, context, timestamp, result;
			    const later = function() {
			        // 据上一次触发时间间隔
			        const last = +new Date() - timestamp;

			        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
			        if (last < wait && last > 0) {
			            timeout = setTimeout(later, wait - last);
			        } else {
			            timeout = null;
			            // 如果设定为immediate===true，因为开始已经调用过了此处无需调用
			            if (!immediate) {
			                result = func.apply(context, args);
			                if (!timeout) context = args = null;
			            }
			        }
			    };
			    return function(...args) {
			        context = this;
			        timestamp = +new Date();
			        const callNow = immediate && !timeout;
			        // 如果延时不存在，重新设定延时
			        if (!timeout) timeout = setTimeout(later, wait);
			        if (callNow) {
			            result = func.apply(context, args);
			            context = args = null;
			        }

			        return result;
			    };
			},
			//视频
			onPlayerPlay(player) {
				this.onSlicePlay()
				this.watchPlayProgress();
				//渲染打点
				this.resolveMark();

			},
			onPlayerPause(player) {
				clearInterval( this.watchPlayTimeOut );
			},
			//表单验证
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.editBol  = false
						var videotime = this.ruleForm.test_time.split( ":" ); // 时间字符分割 
						var videotimeSeconds = parseInt( videotime[ 0 ] * 3600 ) + parseInt( videotime[ 1 ] * 60 ) + parseInt( videotime[ 2 ] ); // 时间转成秒数
						if (videotimeSeconds === 0) {
							return this.$message.error('请选择开始时间')
						}

						this.$refs.videoPlayer.player.pause();
						if (this.ruleForm.test_data.length === 0) {
							let newTabIndex = this.ruleForm.test_data.length + 1;
							this.editableTabsEle.title = `第${newTabIndex}题`;
							this.editableTabsEle.name = (newTabIndex-1).toString();
							this.tabTempIndex = (newTabIndex-1).toString();
							this.ruleForm.test_data.push( deep_clone(this.editableTabsEle) );
						}

						this.questionVisible = true
					} else {
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.ruleForm.test_time = '';
				this.ruleForm.test_name = '';
			},
			handleTabsEdit(targetName, action) {
			
				if (action === 'add') {
					let newTabIndex = this.ruleForm.test_data.length + 1;
					this.editableTabsEle.title = `第${newTabIndex}题`;
					this.editableTabsEle.name = (newTabIndex-1).toString();
					this.editableTabsEle.answer = 'A';
					this.tabTempIndex = (newTabIndex-1).toString();

					
					this.ruleForm.test_data.push( deep_clone(this.editableTabsEle) );
					console.log(this.ruleForm,9999);
				}
				if (action === 'remove') {
					if (this.ruleForm.test_data.length ===1) { return }
					var tabs = deep_clone( this.ruleForm.test_data );
					var newtabs =  [];
					var continue_ornot = false;
					var ivn = 0;

					for (var i = 0; i <=  tabs.length - 1; i++) {
						if( tabs[i].name === targetName){

							continue_ornot = true;
							if( parseInt( this.tabTempIndex ) > 0 && i === parseInt( this.tabTempIndex ) ){
								this.tabTempIndex = (parseInt( this.tabTempIndex )-1).toString()
							}else if( parseInt( this.tabTempIndex ) > i ){
								this.tabTempIndex = (parseInt( this.tabTempIndex )-1).toString()
							}
							continue;
						}else{
							ivn = ivn+1;
							if( continue_ornot ){
								tabs[i].title = `第${ivn}题`;
								tabs[i].name = (ivn-1).toString();
							}
							newtabs.push( tabs[i] );
						}
					}
					this.ruleForm.test_data = deep_clone( newtabs );
								
				}
			
			},
		}
	}
</script>